package com.hung.pro.iFlashCards.ui;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Resource manager
 * User: hung
 * Date: 2008/05/08
 * Time: 21:13:24
 * To change this template use File | Settings | File Templates.
 */
public class Resources {
    private static String configFile = "";
    private static Properties properties;
    private static Locale locale;

    static {
        //load properties
        loadProperties();
        //load locale
        String lang = "";
        if (properties != null) {
            lang = properties.getProperty("lang");
        }
        try {
            if (lang != null && !"".equals(lang)) {
                locale = new Locale(lang);
            }
            else{
                locale = new Locale("en");
            }
        }
        catch (Exception e) {

            try {
                locale = new Locale("en");
            } catch (Exception e1) {
                locale = Locale.getDefault();
            }
        }
    }

    private static void loadProperties() {

        try {
            String userHomeDir = System.getProperty("user.home", ".");
            String systemDir = userHomeDir + "/.iFlashCards";
            configFile = systemDir + "/iFlashCards.config";
            properties = new Properties();
            properties.load(new FileInputStream(configFile));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String getString(String key) {
        String value = ResourceBundle.getBundle("com/hung/pro/iFlashCards/iFlashCards", locale).getString(key);
        return value;
    }

    public static Locale getLocale() {
        return locale;
    }

    public static void setString(String key, String value) {
        FileOutputStream fileOutput = null;
        try {
            properties.setProperty(key, value);
            fileOutput = new FileOutputStream(configFile);
            properties.store(fileOutput, new Date().toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutput != null) {
                try {
                    fileOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
